// import { promisify } from 'util';
// import { all as convert } from 'heic-convert';
// import fs from 'fs';
// import path from 'path';

const { promisify } = require('util');
const convert = require('heic-convert');
const fs = require('fs');
const path = require('path');
const { readdir } = require('fs/promises');

class HeicConvertCompress {
    constructor(input, output, format, quality, verbose, force) {
        this.input = input;
        this.output = output;
        this.format = format;
        this.quality = quality;
        this.verbose = verbose;
        this.force = force;
        this.run();
    }

    async run() {
        const files = await this.findHEICFilesIterative(this.input);
        // 检查保存目录是否存在
        if (!fs.existsSync(this.output)) {
            fs.mkdirSync(this.output);
        }
        let processFileNumber = 0;
        for (let i = 0; i < files.length; i++) {
            const pathname = files[i];
            const saveFile = `${path.basename(pathname).split('.').shift()}.${this.format}`;
            const output = path.join(this.output, saveFile);
            
            if (fs.existsSync(output) && this.force === false) {
                if (this.verbose === true) {
                    console.log(`Processing file: ${path.basename(pathname)} => output/${saveFile} exists`)
                }

                continue;
            }

            if (this.verbose) {
                console.log(`Processing file: ${path.basename(pathname)} => output/${saveFile}`)
            }
            
            // HEIC图片格式转换
            const inputBuffer = await promisify(fs.readFile)(pathname);
            const outputBuffer = await convert({
                buffer: inputBuffer, // the HEIC file buffer
                format: this.format.toUpperCase(),      // output format
                quality: this.quality     // the jpeg compression quality, between 0 and 1
            });

            await promisify(fs.writeFile)(output, outputBuffer);

            ++processFileNumber;
        }

        console.log(`A total of ${files.length} files were found, and ${processFileNumber} files were processed`)
    }

    async findHEICFilesIterative(rootDir = '.') {
        const heicFiles = [];
        const directories = [rootDir];
        
        while (directories.length > 0) {
            const currentDir = directories.pop();
            
            try {
                const items = await readdir(currentDir, { withFileTypes: true });
                
                for (const item of items) {
                    // 忽略隐藏文件
                    if (item.name.startsWith('.')) continue;
                    
                    const fullPath = path.join(currentDir, item.name);
                    
                    if (item.isDirectory()) {
                        // 将子目录加入待处理列表
                        directories.push(fullPath);
                    } else if (item.isFile() && item.name.toLowerCase().endsWith('.heic')) {
                        heicFiles.push(fullPath);
                    }
                }
            } catch (error) {
                console.warn(`无法访问目录: ${currentDir}`, error.message);
                // 继续处理其他目录
            }
        }
        
        return heicFiles;
    }
}

module.exports = HeicConvertCompress;

